package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.jdbc.Work;

import po.tree_one;
import po.tree_three;
import po.tree_two;

public class PeizhiDaoImp implements PeizhiDao{

	private SessionFactory sessionFactory;
	  
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	@Override
	public String addPeizhi(Set<tree_one> tree_ones,Set<tree_two> tree_twos,Set<tree_three> tree_threes) {
		// TODO Auto-generated method stub
		try {
			Session session=this.sessionFactory.getCurrentSession();
			 Work work3=new Work(){
				public void execute(Connection connection)throws SQLException{
					PreparedStatement stmt=connection.prepareStatement("delete from tree_three");
					stmt.executeUpdate();

				}
			};
			Work work2=new Work(){
				public void execute(Connection connection)throws SQLException{
					PreparedStatement stmt=connection.prepareStatement("delete from tree_two");
					stmt.executeUpdate();

				}
			};
			
			Work work1=new Work(){
				public void execute(Connection connection)throws SQLException{
					PreparedStatement stmt=connection.prepareStatement("delete from tree_one");
					stmt.executeUpdate();

				}
			};
			session.doWork(work3);
			session.doWork(work2);
			session.doWork(work1);
			
			for(Iterator<tree_one> iter1=tree_ones.iterator();iter1.hasNext();){
				tree_one tree1=iter1.next();
				session.merge(tree1);
				
	
			}
			for(Iterator<tree_two> iter2=tree_twos.iterator();iter2.hasNext();){
				tree_two tree2=iter2.next();
				session.merge(tree2);
			}
			for(Iterator<tree_three> iter3=tree_threes.iterator();iter3.hasNext();){
				tree_three tree3=iter3.next();
				session.merge(tree3);
			}
			
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return "add_error";
		}
		
		return "add_success";
	}
	@Override
	public List<tree_one> list_tree1() {
		// TODO Auto-generated method stub
		List<tree_one> tree1List=this.sessionFactory.getCurrentSession().createQuery("from tree_one").list();
		return tree1List;
	}
	@Override
	public List<tree_two> list_tree2() {
		// TODO Auto-generated method stub
		List<tree_two> tree2List=this.sessionFactory.getCurrentSession().createQuery("from tree_two").list();
		return tree2List;
	}
	@Override
	public List<tree_three> list_tree3() {
		// TODO Auto-generated method stub
		List<tree_three> tree3List=this.sessionFactory.getCurrentSession().createQuery("from tree_three").list();
		return tree3List;
	}

}
